#coding=utf-8

import cgi
import os
import datetime
import time

from google.appengine.ext.webapp import template 
from google.appengine.ext.blobstore import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import images
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson

global NUMBER
NUMBER = 10

#start = [2010,4,29]
#end = time.localtime()[0:3]

certified = [
    users.User("guoxiaokun@gmail.com"),
    users.User("lvjiyu@gmail.com")
]

class Photo(db.Model):
    author = db.UserProperty()
    date = db.DateTimeProperty()
    tag = db.StringProperty()
    comment = db.StringProperty(multiline=True)
    data = db.BlobProperty()
    preview = db.BlobProperty()


class MainPage(webapp.RequestHandler):
  def get(self):

    user = users.get_current_user() 
    if user:
        if user in certified:
            pass
        else:
            self.response.out.write("Thank you for visiting" + user.nickname())
        url_linka = users.create_logout_url(self.request.uri)
        url_linktext = 'Logout '+user.nickname()
    else:
        url_linka = users.create_login_url(self.request.uri)
        url_linktext = 'Login'
        self.redirect(users.create_login_url(self.request.uri)) 

    global NUMBER 
    query_str = "SELECT * FROM Photo WHERE author = user ORDER BY date DESC LIMIT " + str(NUMBER)
    photos = db.GqlQuery ("SELECT * FROM Photo WHERE author = :muser ORDER BY date DESC LIMIT "+str(NUMBER), muser=user) 
    keys = [str(i.key()) for i in photos]
    template_values = {
      'keys': keys, 
      'url_linka':url_linka,
      'url_linktext':url_linktext,
      } 
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

#class FileUpLoad(blobstore_handlers.BlobstoreUploadHandler):
class FileUpLoad(webapp.RequestHandler):
    def post(self):
        photo = Photo()
        if users.get_current_user():
            photo.author = users.get_current_user()
        img = self.request.get("file")
        if img:
            photo.data = db.Blob(img)
            photo.preview = db.Blob(images.resize(img, 100, 100))
            photo.put()
        self.redirect('/')

class Preview(webapp.RequestHandler):        
    def get(self):
        photo = db.get(self.request.get("img_id"))
        if photo.data and (users.get_current_user() in certified):
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(photo.preview)
        else:
            self.response.out.write("No image")
        
class Image(webapp.RequestHandler):        
    def get(self):
        photo = db.get(self.request.get("img_id"))
        if photo.data and (users.get_current_user() in certified):
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(photo.data)
        else:
            self.response.out.write("No image")
        
class RPCHandler(webapp.RequestHandler):
    """ Allows the functions defined in the RPCMethods class to be RPCed."""
    def __init__(self):
        webapp.RequestHandler.__init__(self)
        self.methods = RPCMethods()

    def get(self):
        func = None

        action = self.request.get('action')
        if action:
            if action[0] == '_':
                self.error(403) # access denied
                return
            else:
                func = getattr(self.methods, action, None)

        if not func:
            self.error(404) # file not found
            return

        args = ()
        while True:
            key = 'arg%d' % len(args)
            val = self.request.get(key)
            if val:
                args += (simplejson.loads(val),)
            else:
                break
        result = func(*args)
        self.response.out.write(simplejson.dumps(result))


class RPCMethods:
    """ Defines the methods that can be RPCed.
    NOTE: Do not allow remote callers access to private/protected "_*" methods.
    """

    def Del(self, *args):
        
        a=[]
        for i in args[0]:
            a.append( db.get(i).author)
            db.delete(db.get(i))
            
        return "deleted %r, %r"%(args[0], a)

    def set_photo_info(self, *args):
        photo = db.get(args[0][0])
        photo.tag = args[0][1]
        photo.comment = args[0][2]
        photo.put()
        return "%r"%args[0]

    def get_photo_info(self, *args):
        photo = db.get(args[0])
        return {
            'date':"%r"%photo.date,
            'tag':photo.tag,
            'comment':photo.comment
        }

application = webapp.WSGIApplication(
                                     [
                                     ('/', MainPage),
                                     ('/rpc', RPCHandler),
                                     ('/upload', FileUpLoad),
                                     ('/img', Image),
                                     ('/prv', Preview),
                                      ],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

